#!/usr/bin/python
# -*- coding: UTF-8 -*-

import pygame
import random

# 初始化pygame
pygame.init()

# 设置窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("坦克大战")

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
BROWN = (165, 42, 42)
GRAY = (125, 125, 125)

# 设置时钟
clock = pygame.time.Clock()
FPS = 30


class Tank:
    def __init__(self, x, y, color, is_player=True):
        self.x = x
        self.y = y
        self.color = color
        self.is_player = is_player
        self.width = 40
        self.height = 40
        self.speed = 2
        self.health = 100
        self.level = 1
        self.bullets = []
        self.direction = 'up'  # 初始方向

    def draw(self, window):
        pygame.draw.rect(window, self.color, (self.x, self.y, self.width, self.height))
        # 绘制血条
        pygame.draw.rect(window, RED, (self.x, self.y - 10, self.width, 5))
        pygame.draw.rect(window, GREEN, (self.x, self.y - 10, self.width * (self.health / 100), 5))
        # 绘制等级
        font = pygame.font.SysFont(None, 25)
        level_text = font.render(f"Lv: {self.level}", True, BLACK)
        window.blit(level_text, (self.x, self.y - 30))

    def move(self, direction):
        if direction == 'up':
            self.y -= self.speed
        elif direction == 'down':
            self.y += self.speed
        elif direction == 'left':
            self.x -= self.speed
        elif direction == 'right':
            self.x += self.speed
        self.direction = direction

    def shoot(self):
        if len(self.bullets) < 3 + self.level:  # 子弹数量随等级增加
            bullet = Bullet(self.x + self.width // 2, self.y + self.height // 2, self.direction)
            self.bullets.append(bullet)

    def check_collision(self, other_tank):
        return pygame.Rect(self.x, self.y, self.width, self.height).colliderect(
            pygame.Rect(other_tank.x, other_tank.y, other_tank.width, other_tank.height))

    def take_damage(self, damage):
        self.health -= damage
        if self.health <= 0:
            self.health = 0
            self.explode()

    def explode(self):
        print("Tank exploded!")
        # 这里可以添加爆炸动画


class Bullet:
    def __init__(self, x, y, direction):
        self.x = x
        self.y = y
        self.direction = direction
        self.speed = 5
        self.radius = 5

    def move(self):
        if self.direction == 'up':
            self.y -= self.speed
        elif self.direction == 'down':
            self.y += self.speed
        elif self.direction == 'left':
            self.x -= self.speed
        elif self.direction == 'right':
            self.x += self.speed

    def draw(self, window):
        pygame.draw.circle(window, YELLOW, (self.x, self.y), self.radius)

    def check_collision(self, tank):
        return pygame.Rect(self.x - self.radius, self.y - self.radius, self.radius * 2, self.radius * 2).colliderect(
            pygame.Rect(tank.x, tank.y, tank.width, tank.height))


class Wall:
    def __init__(self, x, y, wall_type):
        self.x = x
        self.y = y
        self.width = 40
        self.height = 40
        self.wall_type = wall_type  # 'earth' or 'metal'
        self.health = 3 if wall_type == 'earth' else float('inf')

    def draw(self, window):
        color = BROWN if self.wall_type == 'earth' else GRAY
        pygame.draw.rect(window, color, (self.x, self.y, self.width, self.height))

    def take_damage(self):
        if self.wall_type == 'earth':
            self.health -= 1
            if self.health <= 0:
                return True  # 墙体被摧毁
        return False


class PowerUp:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width = 20
        self.height = 20

    def draw(self, window):
        pygame.draw.polygon(window, YELLOW, [(self.x, self.y + self.height // 2),
                                             (self.x + self.width // 2, self.y),
                                             (self.x + self.width, self.y + self.height // 2),
                                             (self.x + self.width // 2, self.y + self.height)])

    def check_collision(self, tank):
        return pygame.Rect(self.x, self.y, self.width, self.height).colliderect(
            pygame.Rect(tank.x, tank.y, tank.width, tank.height))


def main():
    player_tank = Tank(100, 100, GREEN)
    enemy_tank = Tank(500, 500, RED, is_player=False)
    walls = [Wall(random.randint(0, WINDOW_WIDTH // 40 - 1) * 40,
                  random.randint(0, WINDOW_HEIGHT // 40 - 1) * 40,
                  random.choice(['earth', 'metal'])) for _ in range(int(WINDOW_WIDTH * WINDOW_HEIGHT * 0.3 / 1600))]
    power_ups = []
    last_power_up_time = pygame.time.get_ticks()

    running = True
    while running:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            player_tank.move('up')
        if keys[pygame.K_DOWN]:
            player_tank.move('down')
        if keys[pygame.K_LEFT]:
            player_tank.move('left')
        if keys[pygame.K_RIGHT]:
            player_tank.move('right')
        if keys[pygame.K_SPACE]:
            player_tank.shoot()

        # 更新子弹
        for bullet in player_tank.bullets:
            bullet.move()
            for wall in walls:
                if pygame.Rect(bullet.x - bullet.radius, bullet.y - bullet.radius, bullet.radius * 2, bullet.radius * 2).colliderect(
                        pygame.Rect(wall.x, wall.y, wall.width, wall.height)):
                    if wall.take_damage():
                        walls.remove(wall)
                    player_tank.bullets.remove(bullet)
                    break
            if bullet.check_collision(enemy_tank):
                enemy_tank.take_damage(10)
                player_tank.bullets.remove(bullet)

        # 道具生成
        current_time = pygame.time.get_ticks()
        if current_time - last_power_up_time > 10000:  # 每10秒生成一个道具
            power_ups.append(PowerUp(random.randint(0, WINDOW_WIDTH - 20), random.randint(0, WINDOW_HEIGHT - 20)))
            last_power_up_time = current_time

        # 检测道具碰撞
        for power_up in power_ups:
            if power_up.check_collision(player_tank):
                player_tank.level += 1
                power_ups.remove(power_up)

        # 绘制游戏元素
        window.fill(WHITE)
        player_tank.draw(window)
        enemy_tank.draw(window)
        for wall in walls:
            wall.draw(window)
        for bullet in player_tank.bullets:
            bullet.draw(window)
        for power_up in power_ups:
            power_up.draw(window)

        pygame.display.update()

    pygame.quit()


if __name__ == "__main__":
    main()